<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="auto">
            <EdCreateCard title="工单信息">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-form-item label="工单地址" class="width-100" prop="address" :rules="$validate.validates({required:true,msg:'工单地址不能为空'})">
                        <!-- <EdSelect v-model="form.payCause" :selectParams="selectParamsPayCause"></EdSelect> -->
                        <EdSelect v-model="form.villageId" :selectParams="proParams"></EdSelect>
                        <el-input style="margin-left: 5px" class="flex-input addrssStyle" v-model="form.address" placeholder="请填写期数门牌单元房间号，例：1期1栋1单元1201" maxlength="50"></el-input>
                    </el-form-item>
                    <el-form-item label="工单类型" class="width-50" prop="orderType" :rules="$validate.validates({required:true,msg:'工单类型不能为空'})">
                        <EdSelect v-model="form.orderType" :selectParams="orderTypeParams"></EdSelect>
                    </el-form-item>
                    <el-form-item label="工单内容" class="width-80" prop="serveDesc" :rules="$validate.validates({required:true,msg:'工单内容不能为空'})">
                        <el-input placeholder="请输入工单内容描述" class="flex-input" type="textarea" v-model="form.serveDesc" :rows="6"  maxlength="500" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item class="width-100" label="图片上传">
                        <!-- <WisdomUploadSingle v-model="form.serveImages" @pic-url="picUrl($event, 'serveImages')" ref="edUploadSingle"></WisdomUploadSingle> -->
                        <el-upload
                            class="upload-img"
                            accept="image/*"
                            :action="action"
                            list-type="picture-card"
                            :limit="3"
                            :multiple="true"
                            :file-list="fileList"
                            :before-upload="beforeImgUpload"
                            :on-preview="handleImgPreview"
                            :on-success="handleImgSuccess"
                            :on-remove="handleImgRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                        <p class="labelFont">请上传5M以内，格式为jpeg、jpg、png、gif的图片，至多3张</p>
                    </el-form-item>
                    <!-- <el-form-item label="预约上门时间" class="width-50" prop="appointmentTime" :rules="$validate.validates({required:true,msg:'预约上门时间不能为空'})">
                        <EdDateTimePickerRange v-model="form.appointmentTime" pickerOptions="days" :pickerParams="pickerRangeParams"></EdDateTimePickerRange>
                    </el-form-item> -->
                    <el-form-item label="报单人" prop="proposer" :rules="$validate.validates({required:true,msg:'报单人不能为空'})">
                        <el-input class="flex-input phoneStyle" v-model="form.proposer" placeholder="姓名" maxlength="50"></el-input>
                        <!-- <el-input style="margin-left: 10px" class="flex-input phoneStyle" v-model="form.proposerPhone" placeholder="电话"></el-input> -->
                    </el-form-item>
                    <el-form-item label="" prop="proposerPhone" :rules="$validate.validates({required:true,msg:'报单人电话不能为空'})" label-width="0">
                        <!-- <el-input class="flex-input phoneStyle" v-model="form.proposer" placeholder="姓名"></el-input> -->
                        <el-input class="flex-input phoneStyle" v-model="form.proposerPhone" placeholder="电话"></el-input>
                    </el-form-item>

                    <!-- <el-form-item label="接单人" class="width-100" prop="repairerId"  :rules="$validate.validates({required:true,msg:'接单人不能为空'})">
                        <el-select v-model="form.repairerId" @change="handleRepairChange" :placeholder="recPersonParams.placeholder" clearable>
                            <el-option v-for="item in recPersonParams.options" :label="item['name']" :value="item['id']" :key="item['id']">
                               <el-radio v-model="radio" :label="item.id">
                                    <span class="name">{{item.name}}</span>
                                    <span class="phone">{{item.mobile}}</span>
                                </el-radio>
                            </el-option>
                        </el-select>
                    </el-form-item>                    -->
                </div>
                <el-form-item class="form_btns">
                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">确定</el-button>
                    <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router)">取消</el-button>
                </el-form-item>
            </EdCreateCard>
        </el-form>
          <EdDialog :width="'420px'" :title="'提交失败'" :showSubmitBtn="false" :showCloseBtn="false"  class="errorDialog" v-if="errorVisible">
           <el-result icon="error" :subTitle="errorVisible_desc">
            <template slot="extra">
                <el-button class="ed-button ed_black-bottom" @click="handleErrSubmit">确定</el-button>
            </template>
            </el-result>
        </EdDialog>
    </div>
</template>

<script>
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdDateTimePicker from 'src/components/EdDateTimePicker.vue'
    import EdDateTimePickerRange from 'src/components/EdDateTimePickerRange.vue'
    import WisdomUploadSingle from "src/components/WisdomUploadSingle.vue";
    import EdSelect from 'src/components/EdSelect.vue'
    import { defineComponent } from 'vue'
    import { getDictByCode } from "src/api/dictionaries";
    import { orderDetail, orderAdd, orderUpdate, getrRepairerData, getProjectList } from "./api.js";
    import EdDialog from 'src/components/EdDialog.vue';
    export default defineComponent({
        name: "companyCreate",
        components: { EdCreateCard, EdDateTimePickerRange, WisdomUploadSingle, EdSelect, EdDateTimePicker, EdDialog},
        data(){
            return{
                form:{
                    villageId: '',
                    address: '',
                    orderType: '',
                    serveDesc: '',
                    serveImages: [],
                    appointmentTime: '',
                    proposer: '',
                    proposerPhone: '',
                    // repairerId: '',
                    // repairer: '',
                    // repairerPhone: '',
                    // isConfirmed: true
                },
                pickerRangeParams:{
                    valueFormat:"yyyy-MM-dd HH:mm"
                },
                disabled:false,
                isUpdate: false,
                orderTypeParams: {
                    placeholder:"请选择工单类型",
                    options: [],
                    // props: {label:"desc", value:"type"}
                },
                recPersonParams: {
                    placeholder:"请选择",
                    options: [{
                        id: 9,
                        name: '小里(管家)',
                        mobile: '13787874511',
                    },
                    {
                        id: 8,
                        name: '小王(管家)',
                        mobile: '13787874511',
                    }],
                    // props: {label:"name", value:"id"}
                },
                proParams: {
                    placeholder:"请选择所属项目",
                    options: [],
                    props: {label:"villageName", value:"villageId"}
                },
                dialogImageUrl: '',
                dialogVisible: false,
                action: '',
                imgList: [],
                fileList: [],
                // 接单人select
                radio: '',
                // 提交失败 dialog
                errorVisible: false,
                errorVisible_desc: '您所选择的工单类型没有对应处理人，请在“物业人员管理”中选择与工单类型匹配的职能',
                uploadStyle: 'inline-block'
            }
        },
        activated(){
            // 接单人
            // getrRepairerData().then((res) =>{
            //     this.recPersonParams.options = res.data;
            // })
            // 获取 所属项目
            getProjectList({pageSize: 999999}).then(res=>{
                this.proParams.options = res.data.records;
            })
            // 获取 工单类型(物业人员-所属职能)
            getDictByCode('member_functions_type').then(res=>{
                this.orderTypeParams.options = res.data.items;
            })
            this.action = this.$baseApi + "/infra/file/upload";
            if(this.$route.query.id){
                // 编辑 
                this.isUpdate = true;
                this.orderDetail();
            }else {
              
            }
        },
        deactivated(){
            this.form={
                villageId: '',
                address: '',
                orderType: '',
                serveDesc: '',
                serveImages: [],
                appointmentTime: '',
                proposer: '',
                proposerPhone: '',
                // repairerId: '',
                // repairer: '',
                // repairerPhone: '',
                // isConfirmed: true
            }
            this.disabled = false;
            this.fileList = []
            this.imgList = []
            this.$refs.formRef.resetFields()
            this.uploadStyle = 'inline-block'
        },
        // mounted(){
        //     this.action = this.$baseApi + "/infra/file/upload";
        //     if(this.$route.query.id){
        //         // 编辑 
        //         this.isUpdate = true;
        //         this.orderDetail();
        //     }else {
              
        //     }
        // },
        methods:{
            orderDetail(){
                orderDetail({id:this.$route.query.id}).then(response => {
                    if(response.code == 20000) {
                        response.data.serveImages&&response.data.serveImages.forEach((v, i) => {
                            this.fileList.push({ url: v })
                        })

                        this.detailData = response.data; 
                        this.form = {
                            villageId: response.data.villageId.toString(),
                            address: response.data.address,
                            orderType: response.data.orderType,
                            serveDesc: response.data.serveDesc,
                            // appointmentTime: response.data.appointmentTime,
                            // appointmentTime: [response.data.appointmentTimeStart,response.data.appointmentTimeEnd],
                            // appointmentTimeStart: response.data.appointmentTimeStart,
                            // appointmentTimeEnd: response.data.appointmentTimeEnd,
                            proposer: response.data.proposer,
                            proposerPhone: response.data.proposerPhone,
                            // repairerId: response.data.repairerId,
                            // repairer: response.data.repairer,      
                            // repairerPhone: response.data.repairerPhone,
                            // isConfirmed: response.data.isConfirmed,
                        };
                    }
                })
            },
            emitEchoTimeDate($event, name){
                // $event 子组件$emit传的参数 
                console.log('选择--->', $event, name)
                this.form[name]=$event;
            },
            // 图片 上传前
            beforeImgUpload(file){
                // console.log('before-->', file)
                const fileType = file.name.split('.');
                const fileDate = fileType.slice(-1);
                // if (['jpeg', 'jpg', 'png', 'bmp'].indexOf(fileDate[0]) < 0) {
                // if (['jpeg', 'jpg', 'png', 'gif'].indexOf(file.type.split('/')[1]) < 0) {
                //     this.$message.error({ message: '仅支持格式：jpeg、jpg、png、gif!', center: true });
                //     return false
                // }
                if (this.imgList.length > 2) {
                    this.$message.error('最多上传三张图片！')
                    return false;
                }
                const isLt5M = file.size / 1024 /1024 < 5;
                if (!isLt5M) {
                    this.$message.error('上传文件大小不能超过 5MB!');
                }
                return isLt5M;
            },
            // 图片 上传成功
            handleImgSuccess(response, file, fileList){
                let res = file.response;
                if(res&&res.code == 20000){
                    this.imgList.push(res['data'])
                }
                this.uploadStyle = fileList.length==3?'none':'inline-block'
            },
            handleImgChange(file, fileList){
            },
            // 图片 删除
            handleImgRemove(file, fileList) {
                this.imgList = fileList&&fileList.map(v=>{
                    return v['response']? v['response']['data'] : v['url']
                })
                this.uploadStyle = fileList.length==3?'none':'inline-block'
            },
            // 图片 预览
            handleImgPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            // 接单人select
            handleRepairChange(value){
                let obj = this.recPersonParams.options.find((v, i)=>{
                    return v.id == value
                })
                this.form.repairerId = obj['id']
                this.form.repairer = obj['name']
                this.form.repairerPhone = obj['mobile']
            },
            onSubmit(formName){
                 // 去空格
                this.form['address']=this.form['address'].trim();
                this.form['serveDesc']=this.form['serveDesc'].trim();
                this.form['proposer']=this.form['proposer'].trim();
                this.form['proposerPhone']=this.form['proposerPhone'].trim();
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        this.disabled = true;
                        let query = this.form.copy();
                        // query.appointmentTimeStart= this.form.appointmentTime[0];
                        // query.appointmentTimeEnd = this.form.appointmentTime[1];
                        // delete query.appointmentTime;
                        if(this.isUpdate){
                            if(this.imgList.length > 1 )  query['serveImages'] = this.imgList
                            query['orderNo'] = this.detailData['orderNo']
                            orderUpdate(query).then(response => {
                                if(response.code == 20000) {
                                    if(response.desc) {
                                        this.errorVisible_desc = response.desc;
                                        this.errorVisible = true;
                                    }
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '保存成功',
                                        center: true,
                                        duration: 2000,
                                    });
                                    // this.form.id = response.data;
                                    if(this.$route.query.type !=0){
                                        window.setTimeout(() => {
                                            this.$utilsSet.goBack(this.$router);
                                        }, 600)
                                    }
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }else{
                            query['serveImages'] = this.imgList;
                            orderAdd(query).then(response => {
                                if(response.code == 20000) {
                                    if(response.desc) {
                                        this.errorVisible_desc = response.desc;
                                        this.errorVisible = true;
                                    }
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '添加成功',
                                        center: true,
                                        duration: 2000,
                                    });
                                    // this.form.id = response.data;
                                    if(this.$route.query.type !=0){
                                        window.setTimeout(() => {
                                            this.$utilsSet.goBack(this.$router);
                                        }, 600)
                                    }
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }
                    }
                })
            },
            handleErrSubmit(){
                this.errorVisible = false;
            }
        }
    })
</script>

<style scoped lang="scss">
    :deep .el-form-item{
        .el-form-item__content{
            .el-input{
                 input{
                    width: 230px !important;
                }
            }
            .addrssStyle.el-input{
                width: 460px !important;
                .el-input__inner{
                    width: 460px !important;
                }
            }
            .phoneStyle.el-input{
                width: 230px !important;
            }
            .el-textarea{
                width: 690px !important;
            }
            .change_box{
                padding: 15px 30px 10px 10px;
                font-family: 'Noto Sans SC';
                font-style: normal;
                font-weight: 400;
                line-height: 22px;
                 .name{
                    font-size: 14px;
                    color: #606266;
                }
                .phone{
                    font-size: 14px;
                    color: #909399;
                    margin-left: 10px;
                }
            }
        }
        .upload-img .el-upload{
            display: v-bind(uploadStyle)
        }
    }
    .img_center{
        display: flex;
        align-items: center;
    }
    .form_btns{
        // display: flex;
        // justify-content: flex-end;
        // margin-right: 10px;
        margin-left: 47px;
    }

    .name{
        font-size: 14px;
        color: #606266;
    }
    .phone{
        font-size: 14px;
        color: #909399;
        margin-left: 10px;
    }
    .labelFont{
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        color: #989898;
    }
    :deep .errorDialog{
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 500;
        line-height: 22px;    
        .el-dialog__body{
            padding: 0;
            .el-result{
                padding: 0;
                .el-result__icon .icon-error{
                    fill: #F56C6C;
                }
                .el-result__title p{
                    font-size: 14px;
                    color: #606266;
                }
                .el-result__subtitle p{
                    font-size: 14px;
                    color: #606266;
                    line-height: 25px;    
                    margin: 10px 40px 0;
                }
            }
        }
    }
</style>